<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">企业：</label>
                                    <div class="layui-input-inline">
                                        <select name="companyInfoId"></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="postBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                            <!--                            <button id="roleBtnTemplate" class="layui-btn icon-btn layui-btn-normal">模板下载</button>-->
                            <!--                            <button id="roleBtnImport" class="layui-btn icon-btn color-reseda">-->
                            <!--                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入-->
                            <!--                            </button>-->
                            <!--                            <button id="postBtnExport" class="layui-btn icon-btn color-green">导出</button>-->
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="postTable" lay-filter="postTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="postTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="postForm">
    <form lay-filter="postForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>所属企业</label>
            <div class="layui-input-block">
                <select name="companyInfoId" lay-filter="getCompanyInfo" lay-verify="required" required
                        lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>所属部门</label>
            <input name="departmentId" type="hidden"/>
            <div class="layui-input-block" id="selectDepartment">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>所属角色</label>
            <div class="layui-input-block">
                <select name="roleId" id="roleId" lay-filter="getRoleId" lay-verify="required" required lay-search>
                    <option value="">请选择角色</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input"
                       maxlength="20" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>编码</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入编码" type="text" class="layui-input"
                       maxlength="200" lay-verify="required|isOnlyCode" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" class="layui-textarea" maxlength="200"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="postFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;

        // 获取企业数据
        admin.req('user/admin/companyInfo/list', {limit: 9999}, function (res) {
            if (res.code == 200) {
                var html = '<option value="">请选择企业</option>';
                for (var k = 0; k < res.data.length; k++) {
                    html += '<option value="' + res.data[k].id + '">' + res.data[k].name + '</option>';
                }
                $("select[name='companyInfoId']").html(html);
                form.render('select');
            } else {
                layer.msg('获取企业失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        // 渲染表格
        var insTb = table.render({
            elem: '#postTable',
            url: config.base + 'user/admin/post/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'},
                {field: 'code', title: '编码'},
                {field: 'name', title: '名称'},
                {field: 'companyInfoName', title: '所属企业'},
                {field: 'departmentName', title: '所属部门'},
                {field: 'roleName', title: '所属角色'},
                {field: 'remark', title: '备注'},
                {field: 'createTime', sort: true, title: '创建时间'},
                {align: 'center', toolbar: '#postTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if (menuButton.indexOf("搜索") == -1) {
                    $('.layui-form.toolbar').remove();
                }
                if (menuButton.indexOf("修改") == -1) {
                    $("[lay-event='edit']").remove();
                }
                if (menuButton.indexOf("删除") == -1) {
                    $("[lay-event='del']").remove();
                }
            }
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 工具条点击事件
        table.on('tool(postTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                data.eventType = 'edit';
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
        });

        //监听排序
        table.on('sort(postTable)', function (obj) {
            table.reload('postTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 添加按钮点击事件
        $('#postBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '700px',
                offset: '65px',
                title: data ? '修改岗位表' : '添加岗位表',
                content: $('#postForm').html(),
                success: function () {
                    var treeData = [];
                    var getDepartments = function (companyId) {
                        admin.req('user/admin/department/getTreeData', {
                            companyId: companyId,
                            limit: 9999
                        }, function (res) {
                            if (res.code == 200) {
                                treeData = res.data;
                            } else {
                                layer.msg('获取部门失败', {icon: 2, time: 1000});
                            }
                        }, 'GET', false);
                    }


                    var selectedData = function (treeData, targetId) {
                        for (var k = 0; k < treeData.length; k++) {
                            var nodeId = treeData[k].value;
                            if (targetId == nodeId) {
                                treeData[k].selected = true;
                                return;
                            } else {
                                if (treeData[k].children && treeData[k].children != '') {
                                    selectedData(treeData[k].children, targetId);
                                }
                            }
                        }
                    }


                    var xmRender = function (treeData) {
                        xmSelect.render({
                            el: '#selectDepartment',
                            model: {label: {type: 'text'}},
                            radio: true,
                            clickClose: true,
                            filterable: true,
                            tree: {
                                show: true,
                                strict: false,
                                expandedKeys: [-1],
                            },
                            tips: '顶级分类',
                            height: 'auto',
                            data() {
                                return treeData;
                            },
                            on: function (data) {
                                //被选中的select的id,如果没有 -1
                                let departmentId = data.arr.length > 0 ? data.change[0].value : -1;
                                $("input[name='departmentId']").val(departmentId);
                            },
                        });
                    }

                    var xmInit = function (companyId) {
                        getDepartments(companyId);
                        if (data && data.eventType == 'edit') {
                            selectedData(treeData, data.departmentId);
                        }
                        xmRender(treeData);
                    }
                    xmRender([]);


                    admin.req('user/admin/role/getAll', {}, function (res) {
                        if (res.code == 200) {
                            if (res.data.length > 0) {
                                $.each(res.data, function (index, item) {
                                    $("#roleId").append(new Option(item.name, item.id));
                                })
                                form.render('select');
                            }
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');


                    form.val('postForm', data);

                    form.verify({
                        isOnlyCode: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/post/isOnly', {code: value, id: idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET', false);
                            if (!isOnly) {
                                return "编码必须唯一"
                            }
                        },
                        integer: [/^([0-9]\d*|[ \t]*)$/, '格式错误']
                    })

                    // 获取企业数据
                    admin.req('user/admin/companyInfo/list', {limit: 9999}, function (res) {
                        if (res.code == 200) {
                            var html = '<option value="">请选择企业</option>';
                            for (var k = 0; k < res.data.length; k++) {
                                html += '<option value="' + res.data[k].id + '">' + res.data[k].name + '</option>';
                            }
                            $("form select[name='companyInfoId']").html(html);
                            form.render('select');
                            if (data && data.companyInfoId) {
                                form.val('postForm', data);
                            }
                            form.on('select(getCompanyInfo)', function (res) {
                                if (res.value) {
                                    // 获取部门数据
                                    xmInit(res.value);
                                } else {
                                    $("form select[name='departmentId']").html("");
                                    form.render('select');
                                    treeData = [];
                                }
                            })
                        } else {
                            layer.msg('获取企业失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    if (data && data.companyInfoId) {
                        // 获取部门数据
                        xmInit(data.companyInfoId);

                    }
                    // 表单提交事件
                    form.on('submit(postFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'user/admin/post/update' : 'user/admin/post/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('postTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('user/admin/post/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#postBtnExport').click(function () {
            var checkRows = table.checkStatus('postTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>